package com.ctyun.xstore.vod.common;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

public class RequestUtil {

	public static String getQueryString(AbstractGeneralRequest request) {
		StringBuilder sb = new StringBuilder();
		try {
			Field[] fields = request.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				Object fieldValue = field.get(request);
				if (null != fieldValue) {
					sb.append(field.getName()).append("=").append(fieldValue).append("&");
				}
			}
		} catch (IllegalArgumentException | IllegalAccessException ex) {
			throw new IllegalArgumentException(String.format("Request xstore api occurs error:%s", ex.getMessage()));
		}
		String queryString = sb.toString();
		if (queryString.endsWith("&")) {
			return queryString.substring(0, queryString.length() - 1);
		}
		return queryString;
	}

	public static Set<String> getQueryParameter(AbstractGeneralRequest request) {
		Set<String> parameterSet = new HashSet<>();
		try {
			Field[] fields = request.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				Object fieldValue = field.get(request);
				if (null != fieldValue) {
					parameterSet.add(field.getName());
				}
			}
		} catch (IllegalArgumentException | IllegalAccessException ex) {
			throw new IllegalArgumentException(String.format("Request xstore api occurs error:%s", ex.getMessage()));
		}
		return parameterSet;
	}
}
